﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class MaterialsController : ApiController
    {
        static readonly nguyenlieuRepository repository = new nguyenlieuRepository();
        // GET api/materials
        public HttpResponseMessage GetAllMaterials(int page = 1, int rows = 10,string sort = "ma_nguyen_lieu", string order = "asc")
        {
            int offset = (page - 1) * rows;
            var lst = repository.Get(offset, rows).OrderBy(c => c.ma_nguyen_lieu);
            
            //string data = "{\"Result\":\"OK\",\"TotalRecordCount\":4,\"Records\":";
            string data = "{\"total\":" + repository.GetAll().Count() + ",\"rows\":";
            data += lst.ToJSON();
            data += "}";
            var response = this.Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(data, Encoding.UTF8, "application/json");

            return response;
        }

        // GET api/materials/5
        public nguyenlieu GetMaterialById(int id)
        {
            nguyenlieu item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
            }
            return item;
        }

        public IEnumerable<nguyenlieu> GetMaterialByName(string name)
        {
            if (name == "" || name == null)
                return repository.GetAll();
            return repository.GetAll().Where(
                p => string.Equals(p.ten_nguyen_lieu, name, StringComparison.OrdinalIgnoreCase));
            
        }

        // POST api/materials
        public string PostMaterial(nguyenlieu nl)
        {
            nl = repository.Add(nl);
            
            return repository._nguyenlieu.ToJSON();
        }

        // PUT api/materials/5
        public string Put(int ma_nguyen_lieu, nguyenlieu nl)
        {
            nl.ma_nguyen_lieu = ma_nguyen_lieu;
            if (!repository.Update(nl))
            {
                return "ERROR";
            }

            return "OK";
        }

        // DELETE api/materials/5
        public HttpResponseMessage DeleteMaterial(int id)
        {
            repository.Remove(id);
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
}
